package com.focusai.efairy.utils;

import com.focusai.efairy.config.AppDirFileUtil;
import com.focusai.efairy.model.file.FileInfo;

import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Luogw on 2017/8/22.
 */

public class FileUtils {
    private static final String HASH_ALGORITHM = "MD5";
    private static final int RADIX = 10 + 26;

    public static String getKdFileTmpPath(FileInfo fileInfo) {
        if(fileInfo == null) {
            return null;
        }
        String fileName = fileInfo.fileName + "_" + getKdFileAmendPath(fileInfo);

        return AppDirFileUtil.getLogDirPath() + fileName + ".tmp";
    }
    private static String getKdFileAmendPath(FileInfo fileInfo){
        if(null == fileInfo){
            return "";
        }
        return MD5.toMD5(fileInfo.downLoadUrl);
    }
    public static void renameDowloadedFile(String originalPath, String filePath) {
        if(originalPath == null || filePath == null) {
            return ;
        }
        File originalFile = new File(originalPath);
        File reNamedFile = new File(filePath);
        originalFile.renameTo(reNamedFile);
    }

    public static String getMD5Hash(String url){
        byte[] md5 = getMD5(url.getBytes());
        BigInteger bi = new BigInteger(md5).abs();
        return bi.toString(RADIX);
    }
    private static byte[] getMD5(byte[] data) {
        byte[] hash = null;
        try {
            MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
            digest.update(data);
            hash = digest.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hash;
    }
    public static void deleteFile(String filePath){
        File file = new File(filePath);
        if (file.exists()){
            file.delete();
        }
    }
}
